package com.yzion.baselib.dialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.Window
import androidx.annotation.LayoutRes
import androidx.annotation.StringRes
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.ThreadUtils
import com.yzion.baselib.R
import com.yzion.baselib.activity.BaseActivity
import com.yzion.baselib.app.BaseApp
import com.yzion.baselib.app.IAppProvider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel

/**
 * ZJJ
 * 实现自定义弹窗可继承该类，如显示的弹窗在BaseActivity框架内，推荐使用 BaseDialogFragment
 */
abstract class BaseDialog(
    context: Context,
    themeId: Int = R.style.DialogFullScreen
) : Dialog(
    context, themeId
) {

    private var baseLoadingDialog: BaseLoadingDialog? = null
    lateinit var view: View

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        view = layoutInflater.inflate(getLayoutId(), null)
        setContentView(view)
        baseLoadingDialog =
            (context.applicationContext as IAppProvider).createLoadingDialog(context) as BaseLoadingDialog
        initView()
        initData()
    }

    /**
     * 默认样式的加载弹窗，可以通过复写BaseApp中的createLoadingDialog来自定义样式，具体参见源码
     */
    open fun showLoading(text: String? = null): BaseLoadingDialog? {
        ThreadUtils.runOnUiThread {
            baseLoadingDialog?.setLoadingTip(text)?.show()
        }
        return baseLoadingDialog
    }

    open fun hideLoading() {
        ThreadUtils.runOnUiThread {
            try {
                baseLoadingDialog?.dismiss()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    open fun initData() {}
    protected abstract fun initView()

    @LayoutRes
    protected abstract fun getLayoutId(): Int

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
    }

}
